$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'material/material/list',
        datatype: "json",
        colModel: [
            { label: 'materialId', name: 'materialId', index: 'material_id', width: 50, align:'center', key: true, hidden:true},
            { label: '操作', name: 'operation', index: 'material_code', width: 60, align:'center',
                formatter:function(value, options, row){
                    var html = '<li class="dropdown" style="list-style: none;position: absolute;width: 60px;"><a href="#" style="margin:0 auto;" class="dropdown-toggle" style="" data-toggle="dropdown">操作<b class="caret"></b></a>';
                    html += '<ul class="dropdown-menu"  style="min-width:100%;font-size: 12px;">';
                    var operations = [];
                    operations.push('<li><a href="javascript:;" onclick="vm.audit('+ row.materialId +');">审核</a></li><li class="divider"></li>');
                    operations.push('<li><a href="javascript:;" onclick="vm.update('+ row.materialId +','+ row.status +');">修改</a></li><li class="divider"></li>');
                    operations.push('<li><a href="javascript:;" onclick="vm.del('+ row.materialId +');">删除</a></li><li class="divider"></li>');
                    html += operations.join("")
                    html += '</ul></li>';
                    return html;
                }
            },
            { label: '耗材编号', name: 'materialCode', index: 'material_code', align:'center', width: 80 },
            { label: '耗材名称', name: 'materialName', index: 'material_name', align:'center', width: 70 },
            { label: '分类名称', name: 'categoryName', width: 80, align:'center' },
            { label: '发布状态', name: 'status', index: 'status', width: 60,align: 'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userData = $("#" + options.gid).jqGrid('getGridParam', 'userData');
                    $.each(userData.materialStatusEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
            },
            { label: '计量单位', name: 'unit', index: 'unit', width: 50, align: 'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userData = $("#" + options.gid).jqGrid('getGridParam', 'userData');
                    $.each(userData.materialUnitEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
            },
            { label: '展示单位', name: 'showUnit', index: 'show_unit', align:'center', width: 50 },
            { label: '型号', name: 'materialModel', index: 'material_model', align:'center', width: 80 },
            { label: '规格', name: 'specifications', index: 'specifications', align:'center', width: 80 },
            { label: '长(m)', name: 'length', index: 'length', align:'center', width: 50 },
            { label: '宽(m)', name: 'width', index: 'width', align:'center', width: 50 },
            { label: '克重(g)', name: 'weight', index: 'weight', align:'center', width: 50 },
            { label: '审核人', name: 'auditName', index: 'audit_name', align:'center', width: 50 },
            { label: '审核时间', name: 'auditTime', index: 'audit_time', align:'center', width: 100 },
            { label: '更新人', name: 'updateName', index: 'update_name', align:'center', width: 50 },
            { label: '更新时间', name: 'updateTime', index: 'update_time', align:'center', width: 100 },
            { label: '创建人', name: 'createName', index: 'create_name', align:'center', width: 50 },
            { label: '创建时间', name: 'createTime', index: 'create_time', align:'center', width: 100 }
        ],
        viewrecords: true,
        height: window.innerHeight - 150,
        rowNum: 20,
        rowList : [20,40,80],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        // multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData",
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function() {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});

            vm.e.materialUnitList = $("#jqGrid").jqGrid('getGridParam', 'userData').materialUnitEnum;
            vm.e.materialStatusEnumList =  $("#jqGrid").jqGrid('getGridParam', 'userData').materialStatusEnum;
        }
    });
    vm.getDataMaterialCategory();
});

//耗材分类树
var ztree;
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "categoryId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            name: "categoryName",
            url:"nourl"
        },
    }
};

var data_ztree;
var data_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "categoryId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            name: "categoryName",
            url:"nourl"
        },
    },
    callback: {
        onClick: zTreeOnClick,
    }
};

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        material:{
            categoryId:null,
            categoryName:null,
            unit:null,
            delete:false,
			materialName:null
        },
        mark:{
            materialName:false,
            categoryId:false,
            categoryName:false,
            unit:false,
            showUnit:false,
            materialModel:false,
            specifications:false,
            length:false,
            width:false,
            weight:false
        },
		storeStockMaterialDto:{
			sellerInfoEntity:null
        },
        q:{
            materialName: '',
            status:'',
        },
        e:{
            materialStatusEnumList:[],
            materialUnitList:[]
        },
        options: [
            { id: 0, text: '个' },
            { id: 1, text: '平方米(㎡)' },
            { id: 2, text: '重量(g)' },
            { id: 3, text: '长度(m)' },
            { id: 4, text: '张' }

        ]
    },
	mounted: function () {
		this.initData();
	},

    methods: {
		initData : function () {
			// 请求已经存在的 门店名称
			$.get(baseURL + "material/material/selectSellerName", function(r){
				vm.storeStockMaterialDto.sellerInfoEntity = r.userData.selectLists;
			});
		},

        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            //重置
            vm.resetMaterial();
            vm.getMaterialCategory();
        },
        update: function (materialId,status) {
            if(materialId == null){
                return ;
            }
            debugger;
            // if(status == 1){
            //     alert("已审核的不允许修改")
            //     return;
            // }
            vm.showList = false;
            vm.title = "修改";
            //重置
            vm.resetMaterial();
            vm.getInfo(materialId)

            // vm.getMaterialCategory();
        },

		saveOrUpdate: function(event){
            if(vm.validator()){
                return;
            }
			if(vm.material.materialId == null){
				var url = "material/material/save";
				vm.storeStockMaterialDto.materialEntity=vm.material;
				if(vm.checkCost(vm.storeStockMaterialDto)){
					$.ajax({
						type: "POST",
						url: baseURL + url,
						contentType: "application/json",
						data:JSON.stringify(vm.storeStockMaterialDto),
						success: function(r){
							if(r.code === 0){
								alert('操作成功', function(index){
									vm.localRead();
								});
							}else{
								alert(r.msg);
							}
						}
					});
				}
				return false;
			}else{
				var url = "material/material/update";
				vm.storeStockMaterialDto.materialEntity=vm.material;
				$.ajax({
					type:"POST",
					url:baseURL + url,
					contentType: "application/json",
					data: JSON.stringify(vm.storeStockMaterialDto),
					success:function (r) {
						if(r.code == 0){
							alert('操作成功',function (index) {
								vm.reload();
							})
						}else{
							alert(r.msg);
						}
					}
				});
			}
		},
        checkCost:function (storeStockMaterialDto) {
		    var reg = /^[-+]?\d+$/;
		    var ssm =storeStockMaterialDto.sellerInfoEntity.length;
            for(var i = 0;i<storeStockMaterialDto.sellerInfoEntity.length;i++){
                var cost = storeStockMaterialDto.sellerInfoEntity[i].cost;
                if(cost != null) {
					if (!reg.test(cost)) {
						alert("单价只能是数字");
						return false;
					}
					if (cost * 1 < 0) {
						alert("单价必须大于0");
						return false;
					}
				}
            }
            var categoryId = storeStockMaterialDto.materialEntity.categoryId;
            if(categoryId == null){
                alert("请选择分类");
                return false;
            }
            var materialName = storeStockMaterialDto.materialEntity.materialName;
            if(materialName == null){
                alert("请输入耗材名称");
                return false;
            }
			return true;
		},

        importExp: function () {
            if(vm.checkFile()){
				var formData = new FormData();
				var name = $("#upfile").val();
				formData.append("file",$("#upfile")[0].files[0]);
				formData.append("name",name);
				var ssssm = /\.[^\.]+/.exec(name);
				var sb1 = ssssm[0].substring(1,4);
				if(sb1!="xlsx" && sb1!= "xls"){
					alert("请选择正确的excel文件");
					return false;
				}
				$.ajax({
					url: "/material/material/SellerName/upload",
					type: "POST",
					async: false,
					data: formData,
					processData: false,
					contentType: false,
					beforeSend:function () {
						console.log("正在进行,请稍后");
					},
					success:function (r) {
						if(r.code==0){
							alert(r.msg);

						}else{
							alert(r.msg);
							return false;

						}
					}
				});
            }
		},
        checkFile: function () {

		    var file = $("#upfile")[0].files.length;
		    if(file<=0){
		        alert("请选择Excel文件导入");
		        return false;
            }
            return true;
		},


        localRead: function () {
		    location.reload();
		},
        del: function (materialId) {
            if(materialId == null){
                return ;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "material/material/delete",
                    contentType: "application/json",
                    data: JSON.stringify(materialId),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        audit: function(materialId){
            if(materialId == null){
                return ;
            }
            confirm('确定确认耗材审核通过？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "material/material/audit",
                    contentType: "application/json",
                    data: JSON.stringify(materialId),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function(materialId){
            $.get(baseURL + "material/material/info/"+materialId, function(r){
                vm.material = r.material;
                //设置只读
                vm.setReadonly();
                if(r.sellerInfoEntities.length > 0) {
					r.sellerInfoEntities.map(function(value, index){
						if(value.cost) {
							value.isHasValue = true
						}
					})
				}
				vm.storeStockMaterialDto.sellerInfoEntity = r.sellerInfoEntities;
                vm.getMaterialCategory();
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    'materialName':vm.q.materialName,
					'categoryId':null,
                    'status':vm.q.status
                },
            }).trigger("reloadGrid");
        },






        reset: function () {
            vm.q.materialName = '';
            vm.reload();
        },
        getMaterialCategory: function(){
            //加载菜单树
            $.get(baseURL + "material/materialcategory/select", function(r){
                debugger;
                ztree = $.fn.zTree.init($("#materialCategoryTree"), setting, r.materialCategoryList);
                var node = ztree.getNodeByParam("categoryId", vm.material.categoryId);
                if(node != null){
                    ztree.selectNode(node);
                    vm.material.categoryName = node.categoryName;
                }
            })
        },
        getDataMaterialCategory: function(){
            //加载菜单树
            $.get(baseURL + "material/materialcategory/select", function(r){
                data_ztree = $.fn.zTree.init($("#categoryTree"), data_setting, r.materialCategoryList);
            })
        },
        materialCategoryTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择耗材分类",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#materialCategoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级菜单
                    vm.material.categoryId = node[0].categoryId;
                    vm.material.categoryName = node[0].categoryName;
                    layer.close(index);
                }
            });
        },
        validator:function(){
		    debugger;
		    //耗材保存校验
            if(isBlank(vm.material.materialName)){
                alert("耗材名不能为空");
                return true;
            }
            if(isBlank(vm.material.categoryId)){
                alert("分类不能为空");
                return true;
            }
            if(typeof vm.material.unit == "undefined" || vm.material.unit == null || obj == ""){
                alert("计量单位不能为空");
                return true;
            }
            if(isBlank(vm.material.showUnit)){
                alert("展示单位不能为空");
                return true;
            }
            return false;
        },
        resetMaterial(){
            vm.material.categoryId = null;
            vm.material.categoryName = null;
            vm.material.unit = null;
            vm.material.delete = false;
            vm.material.materialName = null;
        },
        setReadonly(){
            for (var markElement in vm.mark) {
                if(!isBlank(vm.material[markElement])){
                    vm.mark[markElement] = true;
                }else{
                    vm.mark[markElement] = false;
                }
            }
            debugger;
            if(vm.mark.unit || vm.material.unit == 0){
                $("#unitSelect").attr('disabled', 'disabled');
            }
        }
    }
});


// 注册下拉选择框
Vue.component('ziyun-select', {
    props: ['options', 'value'],
    template: '<select><slot></slot></select>',
    mounted: function () {
        $(this.$el).select2({ data: this.options }).val(this.value).trigger('change').on('change', function () {
            vm.material.unit = this.value;
        })
    },
    watch: {
        value: function (value) {
            // update value
            $(this.$el).val(value).trigger('change')
        },
        options: function (options) {
            // update options
            $(this.$el).empty().select2({ data: options })
        }
    },
    destroyed: function () {
        $(this.$el).off().select2('destroy')
    }
})

// 耗材分类树点击事件
function zTreeOnClick(event, treeId, treeNode) {
    vm.q.materialName = '';
    var page = $("#jqGrid").jqGrid('getGridParam','page');
    $("#jqGrid").jqGrid('setGridParam',{
        page:page,
        postData:{
            'categoryId': treeNode.categoryId,
        },
    }).trigger("reloadGrid");
};

/**
 * 耗材
 */
function goOrderEdit(rowId) {
    var rowData = $("#jqGrid").jqGrid('getRowData', rowId);
    vm.goOrderEdit(rowData.orderId);
}

function add(rowId) {
    var rowData = $("#jqGrid").jqGrid('getRowData', rowId);
    vm.add();
}